package com.example.blog.service.impl;


import com.example.blog.entity.Tag;
import com.example.blog.exception.ResourceNotFoundException;
import com.example.blog.modules.article.dto.TagDTO;
import com.example.blog.repository.TagRepository;
import com.example.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository tagRepository;

    @Override
    @Transactional
    public TagDTO createTag(TagDTO tagDTO) {
        if (tagRepository.existsByName(tagDTO.getName())) {
            throw new RuntimeException("Tag name already exists");
        }

        Tag tag = new Tag();
        updateTagFromDTO(tag, tagDTO);
        return convertToDTO(tagRepository.save(tag));
    }

    @Override
    @Transactional
    public TagDTO updateTag(Long id, TagDTO tagDTO) {
        Tag tag = tagRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Tag", "id", id));
        
        if (!tag.getName().equals(tagDTO.getName()) && 
            tagRepository.existsByName(tagDTO.getName())) {
            throw new RuntimeException("Tag name already exists");
        }

        updateTagFromDTO(tag, tagDTO);
        return convertToDTO(tagRepository.save(tag));
    }

    @Override
    @Transactional
    public void deleteTag(Long id) {
        Tag tag = tagRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Tag", "id", id));
        tagRepository.delete(tag);
    }

    @Override
    public TagDTO getTagById(Long id) {
        Tag tag = tagRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Tag", "id", id));
        return convertToDTO(tag);
    }

    @Override
    public Page<TagDTO> getAllTags(Pageable pageable) {
        return tagRepository.findAll(pageable).map(this::convertToDTO);
    }

    @Override
    public boolean existsByName(String name) {
        return tagRepository.existsByName(name);
    }

    private void updateTagFromDTO(Tag tag, TagDTO dto) {
        tag.setName(dto.getName());
    }

    private TagDTO convertToDTO(Tag tag) {
        TagDTO dto = new TagDTO();
        dto.setId(tag.getId());
        dto.setName(tag.getName());
        dto.setCreatedAt(tag.getCreatedAt());
        dto.setUpdatedAt(tag.getUpdatedAt());
        return dto;
    }
} 